﻿using UnityEngine;
using System;
using System.IO;
using System.Collections.Generic;
using LitJson;

public class AssetBundleManager : IManager<AssetBundleManager> {

	private JsonData jsonManifest;

	public List<LoadedAssetBundle> LoadedAssetBundles = new List<LoadedAssetBundle>();

	public override bool Init(){

		if (!base.Init ()) {
			return false;
		}

		//解析json配置
		if (this.ReadJsonManifest()) {
			this.MarkInitialized ();
			return true;
		} else {
			return false;
		}
	}

	private bool ReadJsonManifest(){
		var fs = new FileStream (PathHelper.manifestPath, FileMode.Open);
		var sr = new StreamReader (fs);
		string content = sr.ReadToEnd ();
		fs.Close ();
		sr.Close ();

		this.jsonManifest = JsonMapper.ToObject (content);

		return false;
	}

	public override void Reset(){
	}

	public bool LoadAssetBundleDirect(string name, Type type){
		return false;
	}

	public bool LoadAssetBundleDirect<T>(string name){
		return false;
	}

	//注:图集随意加载一个精灵即可，整个texture2d都会加载进来
	private LoadedAssetBundle LoadAssetBundleSelf(string name){

		var assetBundle = AssetBundle.LoadFromFile(Path.Combine(PathHelper.AssetBundlePath, name));
		UnityEngine.Object[] assets = assetBundle.LoadAllAssets();

		foreach (var v in assets)
			Debug.Log ("加载:" + v.ToString());

		if(assets == null || assets[0] == null)
		{
			Debug.LogError ("load asset failure! " + name);
			return null;
		}

		var loadAssetBundle = new LoadedAssetBundle (assetBundle, name, assets, assets[0]);
		this.LoadedAssetBundles.Add (loadAssetBundle);

		return loadAssetBundle;
	}

	private List<LoadedAssetBundle> LoadAssetBundleDependencies(string name){

		List<LoadedAssetBundle> list = new List<LoadedAssetBundle> ();

		var depsArray = this.jsonManifest [name] ["deps"];
		for (int i = 0; i < depsArray.Count; i++) {
			
			var lab = this.LoadAssetBundleSelf ((string)depsArray [i]);

			if(lab != null)
				list.Add (lab);
		}

		return list;
	}

	public LoadedAssetBundle LoadAssetBundleDirect(string name){

		bool hasLoaded = false;

		int loadedListIndex = -1;

		for (int i = 0; i < this.LoadedAssetBundles.Count; i++) {
			if (name.Equals(this.LoadedAssetBundles[i].Name)){
				hasLoaded = true;
				loadedListIndex = i;
				Debug.Log (name + ":hasLoaded!");
			}
		}

		if (hasLoaded) {
			return this.LoadedAssetBundles[loadedListIndex];
		}

		var loadAssetBundleList = this.LoadAssetBundleDependencies (name);
		var loadAssetBundle = this.LoadAssetBundleSelf (name);

		//释放AssetBundle内存镜像
		loadAssetBundle.AssetBundle.Unload (false);

		for (int i = 0; i < loadAssetBundleList.Count; i++) {
			#if UNITY_EDITOR
			loadAssetBundleList [i].refList.Add(loadAssetBundle.Name + loadAssetBundle.GetHashCode());
			Debug.Log(loadAssetBundle.Name + loadAssetBundle.GetHashCode());
			#endif

			loadAssetBundleList [i].Retain ();

			loadAssetBundleList [i].AssetBundle.Unload (false);
		}

		return loadAssetBundle;
	}

	protected override void UpdateManger()
	{
		
	}

}
